﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    Layout = null;
}
<link href="~/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
<style>
    .page-container {
        padding: 15px;
    }
    .search-box {
        margin-bottom: 15px;
        padding: 15px;
        background-color: #f2f2f2;
        border-radius: 4px;
    }
    .tool-box {
        margin-bottom: 15px;
    }
    .layui-table {
        box-shadow: 0 1px 3px rgba(0,0,0,.1);
    }
    .layui-form-label {
        width: 100px;
    }
    .layui-input-block {
        margin-left: 130px;
    }
    .table-operations .layui-btn {
        margin: 2px;
    }
    .layui-layer-content .layui-form {
        padding: 20px 30px 0 0;
    }
</style>
<body>
    <div class="page-container">
        @Html.AntiForgeryToken()
        <div class="tool-box">
            <button class="layui-btn" onclick="addpeople()">
                <i class="layui-icon layui-icon-add-1"></i> 添加用户
            </button>
        </div>

        <table class="layui-table" lay-size="lg">
            <thead>
                <tr>
                    <th>用户姓名</th>
                    <th>用户手机号</th>
                    <th>用户部门</th>
                    <th>用户昵称</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody id="tb">
            </tbody>
        </table>
        <div id="pagination"></div>
    </div>
</body>
<script src="~/scripts/jquery-3.4.1.min.js"></script>
<script src="~/scripts/layui-v2.5.6/layui/layui.js"></script>
<script>
    var form;
    var table;
    var laypage;
    
    layui.use(['layer', 'form', 'table', 'laypage'], function(){
        var layer = layui.layer;
        form = layui.form;
        table = layui.table;
        laypage = layui.laypage;

        // 监听搜索表单提交
        form.on('submit(searchForm)', function(data){
            Show(data.field);
            return false;
        });

        // 监听全选框
        form.on('checkbox(checkAll)', function(data){
            var checked = data.elem.checked;
            $('input[name="userCheckbox"]').prop('checked', checked);
            form.render('checkbox');
        });
    });

    $(function(){
        Show();
    });
    
    function Show(searchParams){
        $.ajax({
            url: "/User/ShowUser",
            type: "GET",
            data: searchParams,
            dataType: "json",
            success: function(res) {
                console.log("返回的数据:", res);
                $("#tb").empty();
                if(res && res.length > 0){
                    var data = res.Data || res;
                    $.each(data, function(index, item){
                        console.log("当前项:", item);
                        var row = `
                            <tr>
                                <td>${item.userName}</td>
                                <td>${item.userPhone}</td>
                                <td>${item.departmentName || '未分配部门'}</td>
                                <td>${item.userNickName}</td>
                                <td class="table-operations">
                                    <button class="layui-btn layui-btn-sm" onclick="editUser(${item.id}, '${item.userName}', '${item.userPhone}', '${item.userNickName}', ${item.departmentId}, '${item.departmentName || ''}')">
                                        <i class="layui-icon layui-icon-edit"></i> 修改
                                    </button>
                                    <button class="layui-btn layui-btn-danger layui-btn-sm" onclick="deleteUser(${item.id})">
                                        <i class="layui-icon layui-icon-delete"></i> 删除
                                    </button>
                                    <button class="layui-btn layui-btn-warm layui-btn-sm" onclick="assignRole(${item.id})">
                                        <i class="layui-icon layui-icon-user"></i> 分配角色
                                    </button>
                                </td>
                            </tr>
                        `;
                        $("#tb").append(row);
                    });
                    form.render('checkbox');
                } else {
                    $("#tb").append('<tr><td colspan="5" style="text-align:center">暂无数据</td></tr>');
                }
            },
            error: function(xhr, status, error) {
                console.log("Error:", error);
                console.log("Status:", status);
                console.log("Response:", xhr.responseText);
                $("#tb").append('<tr><td colspan="5" style="text-align:center">加载失败</td></tr>');
                layer.msg('加载数据失败');
            }
        });
    }

    function addpeople(){
        location.href = "/User/UserPage"
    }

    function deleteUser(id) {
        layer.confirm('确定要删除这个用户吗？', {
            icon: 3,
            title: '确认删除',
            btn: ['确定', '取消']
        }, function(index) {
            // 获取防伪标记
            var token = $('input[name="__RequestVerificationToken"]').val();
            
            $.ajax({
                url: '/User/DeleteUser',
                type: 'POST',
                data: { id: id },
                dataType: 'json',
                headers: {
                    'RequestVerificationToken': token
                },
                success: function(res) {
                    if(res.success) {
                        layer.msg(res.message, {
                            icon: 1,
                            time: 1500
                        }, function() {
                            layer.close(index);
                            Show();  // 刷新列表
                        });
                    } else {
                        layer.msg(res.message || '删除失败，请稍后重试', {icon: 2});
                    }
                },
                error: function(xhr, status, error) {
                    console.log("删除失败 - 状态:", status);
                    console.log("删除失败 - 错误:", error);
                    console.log("删除失败 - 响应:", xhr.responseText);
                    layer.msg('删除失败：服务器错误，请稍后重试', {icon: 2});
                }
            });
        });
    }

    function batchDelete() {
        var selectedIds = [];
        $('input[name="userCheckbox"]:checked').each(function() {
            selectedIds.push($(this).val());
        });

        if (selectedIds.length === 0) {
            layer.msg('请选择要删除的用户');
            return;
        }

        layer.confirm('确定要删除选中的 ' + selectedIds.length + ' 个用户吗？', {
            icon: 3,
            title: '确认批量删除',
            btn: ['确定', '取消']
        }, function() {
            // 这里需要后端支持批量删除的接口
            layer.msg('批量删除功能待实现');
        });
    }

    function assignRole(userId) {
        console.log("开始获取用户角色信息，用户ID:", userId);
        
        // 先获取角色列表，成功后再获取用户角色
        $.ajax({
            url: '/api/app/role-services/role',
            type: 'GET',
            dataType: 'json',
            success: function(roles) {
                console.log("✅ 角色列表获取成功:", roles);
                
                // 获取用户已分配的角色
                $.ajax({
                    url: '/User/GetUserRole',
                    type: 'GET',
                    data: { uid: userId },
                    dataType: 'json',
                    success: function(userRoles) {
                        console.log("✅ 用户角色获取成功:", userRoles);
                        
                        // 后台返回List<int>，直接使用
                        var assignedRoleIds = [];
                        if(Array.isArray(userRoles)) {
                            assignedRoleIds = userRoles.map(function(id) {
                                return parseInt(id); // 确保是整数
                            });
                        }
                        
                        console.log("已分配的角色IDs:", assignedRoleIds);
                        
                        // 显示分配角色弹窗
                        showAssignRoleModal(userId, roles, assignedRoleIds);
                    },
                    error: function(xhr, status, error) {
                        console.log("❌ 用户角色获取失败:");
                        console.log("状态码:", xhr.status);
                        console.log("错误:", error);
                        console.log("响应内容:", xhr.responseText);
                        
                        // 显示错误提示
                        layer.msg('获取用户角色失败，请稍后重试', {
                            icon: 2,
                            time: 2000
                        });
                        
                        // 即使获取用户角色失败，也显示弹窗（不预先勾选）
                        console.log("⚠️ 用户角色获取失败，显示角色选择弹窗（无预选）");
                        showAssignRoleModal(userId, roles, []);
    }
                });
            },
            error: function(xhr, status, error) {
                console.log("❌ 角色列表获取失败:");
                console.log("状态:", xhr.status);
                console.log("错误:", error);
                console.log("响应:", xhr.responseText);
                layer.msg('获取角色列表失败，请稍后重试', {icon: 2});
            }
        });
    }
    
    function showAssignRoleModal(userId, roles, assignedRoleIds) {
        console.log("显示分配角色模态框，参数:", {userId, roles, assignedRoleIds});
            
        // 构建复选框HTML
        var roleCheckboxHtml = '';
        if(roles && roles.length > 0) {
            $.each(roles, function(index, role) {
                // 只显示未删除且状态正常的角色
                if(!role.isDelete) {
                    // 检查角色是否已分配
                    var isChecked = assignedRoleIds.indexOf(role.id) !== -1 ? 'checked' : '';
                    
                    roleCheckboxHtml += `
                        <div class="layui-form-item" style="margin: 6px 0;">
                            <div style="padding: 8px 12px; background: white; border-radius: 4px; border: 1px solid #e6e6e6; transition: all 0.3s; box-shadow: 0 1px 2px rgba(0,0,0,0.05);">
                                <input type="checkbox" name="roleIds" value="${role.id}" title="${role.roleName}" lay-skin="primary" ${isChecked}>
                            </div>
                        </div>
                    `;
                }
            });
        } else {
            roleCheckboxHtml = `
                <div style="text-align: center; padding: 40px 20px; color: #999;">
                    <i class="layui-icon layui-icon-face-cry" style="font-size: 32px; display: block; margin-bottom: 12px; color: #ccc;"></i>
                    <span style="font-size: 14px;">暂无可分配的角色</span>
                </div>
            `;
        }
        
        // 打开分配角色弹窗
        layer.open({
            type: 1,
            title: '<i class="layui-icon layui-icon-user"></i> 分配角色',
            area: ['450px', '400px'],
            resize: false,
            content: `
                <div style="height: 100%; display: flex; flex-direction: column;">
                    <form class="layui-form" style="height: 100%; display: flex; flex-direction: column;">
                        @Html.AntiForgeryToken()
                        <input type="hidden" name="UserId" value="${userId}">
                        
                        <div style="padding: 20px 25px 0 25px; flex-shrink: 0;">
                            <div style="margin-bottom: 15px;">
                                <span style="font-size: 14px; color: #666; font-weight: 500;">
                                    <i class="layui-icon layui-icon-list" style="color: #1E9FFF;"></i> 请选择要分配的角色：
                                </span>
                            </div>
                        </div>
                        
                        <div style="flex: 1; margin: 0 25px; background: #f8f9fa; border-radius: 6px; border-left: 4px solid #1E9FFF; overflow-y: auto; padding: 15px;">
                            ${roleCheckboxHtml}
                        </div>
                        
                        <div style="padding: 15px 25px; border-top: 1px solid #eee; text-align: center; flex-shrink: 0;">
                            <button class="layui-btn layui-btn-normal" lay-submit lay-filter="assignRoleForm" style="padding: 0 30px; margin-right: 10px;">
                                <i class="layui-icon layui-icon-ok"></i> 确定分配
                            </button>
                            <button type="button" class="layui-btn layui-btn-primary" onclick="layer.closeAll()" style="padding: 0 30px;">
                                <i class="layui-icon layui-icon-close"></i> 取消
                            </button>
                        </div>
                    </form>
                </div>
            `,
            success: function(layero, index){
                // 重新渲染表单元素
                form.render('checkbox');
                
                // 监听表单提交
                form.on('submit(assignRoleForm)', function(data) {
                    var selectedRoleIds = [];
                    $('input[name="roleIds"]:checked').each(function() {
                        selectedRoleIds.push(parseInt($(this).val()));
                    });
                    
                    if(selectedRoleIds.length === 0) {
                        layer.msg('请至少选择一个角色', {icon: 2});
                        return false;
                    }
                    
                    console.log("用户ID:", userId);
                    console.log("选中的角色IDs:", selectedRoleIds);
                    
                    // 准备传递给后台的数据 - 使用表单数据格式
                    var formData = new FormData();
                    formData.append('UserId', parseInt(userId));
                    
                    // 添加多个角色ID
                    for(var i = 0; i < selectedRoleIds.length; i++) {
                        formData.append('RoleId', selectedRoleIds[i]);
                    }
                    
                    // 获取防伪标记并添加
                    var token = $('input[name="__RequestVerificationToken"]').val();
                    formData.append('__RequestVerificationToken', token);
                    
                    console.log("准备保存的数据:");
                    console.log("UserId:", userId);
                    console.log("RoleIds:", selectedRoleIds);
                    
                    // 调用后台接口保存用户角色关系
                    $.ajax({
                        url: '/User/AddUserRole',
                        type: 'POST',
                        data: formData,
                        processData: false,
                        contentType: false,
                        beforeSend: function() {
                            console.log("发送请求到:", '/User/AddUserRole');
                            console.log("使用FormData格式发送请求");
                        },
                        success: function(res) {
                            console.log("角色分配响应:", res);
                            console.log("响应类型:", typeof res);
                            
                            // 后台返回1表示成功
                            if(res === 1 || res === "1") {
                                layer.msg('角色分配成功', {
                                    icon: 1,
                                    time: 1500
                                }, function() {
                                    layer.close(index);
                                });
                            } else {
                                console.log("分配失败，返回值:", res);
                                layer.msg('角色分配失败，请检查后台日志', {icon: 2});
                            }
                        },
                        error: function(xhr, status, error) {
                            console.log("=== AJAX请求失败详细信息 ===");
                            console.log("状态码:", xhr.status);
                            console.log("状态:", status);
                            console.log("错误:", error);
                            console.log("响应文本:", xhr.responseText);
                            console.log("请求URL:", '/User/AddUserRole');
                            console.log("===============================");
                            
                            var errorMsg = '';
                            if (xhr.status === 404) {
                                errorMsg = '接口不存在 (404)';
                            } else if (xhr.status === 400) {
                                errorMsg = '请求参数错误 (400)';
                            } else if (xhr.status === 500) {
                                errorMsg = '服务器内部错误 (500)';
                            } else if (xhr.status === 0) {
                                errorMsg = '网络连接失败';
                            } else {
                                errorMsg = '请求失败 (' + xhr.status + ')';
                            }
                            
                            layer.msg('角色分配失败：' + errorMsg, {icon: 2});
                        }
                    });
                    
                    return false;
                });
            }
        });
    }



    function editUser(id, userName, userPhone, userNickName, departmentId, departmentName) {
        layer.open({
            type: 1,
            title: '修改用户',
            area: ['500px', '400px'],
            content: `
                <form class="layui-form" style="margin: 20px;">
                    @Html.AntiForgeryToken()
                    <input type="hidden" name="Id" value="${id}">
                    <div class="layui-form-item">
                        <label class="layui-form-label">用户姓名</label>
                        <div class="layui-input-block">
                            <input type="text" name="UserName" value="${userName}" required lay-verify="required" placeholder="请输入用户姓名" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">手机号</label>
                        <div class="layui-input-block">
                            <input type="text" name="UserPhone" value="${userPhone}" required lay-verify="required|phone" placeholder="请输入手机号" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">用户昵称</label>
                        <div class="layui-input-block">
                            <input type="text" name="UserNickName" value="${userNickName}" required lay-verify="required" placeholder="请输入用户昵称" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label required">部门</label>
                        <div class="layui-input-block">
                            <select name="DepartmentId" id="editDepartmentSelect" lay-verify="required" lay-reqText="请选择部门">
                                <option value="">请选择部门</option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-input-block">
                            <button class="layui-btn" lay-submit lay-filter="editUserForm">
                                <i class="layui-icon layui-icon-ok"></i> 立即提交
                            </button>
                            <button type="reset" class="layui-btn layui-btn-primary">
                                <i class="layui-icon layui-icon-refresh"></i> 重置
                            </button>
                        </div>
                    </div>
                </form>
            `,
            success: function(layero, index){
                // 动态加载部门数据
                $.ajax({
                    url: '/InterviewMenagement/GetDepartmentModel',
                    type: 'GET',
                    dataType: 'json',
                    success: function(departments) {
                        console.log('获取部门数据成功:', departments);
                        var departmentSelect = layero.find('#editDepartmentSelect');
                        
                        // 清空现有选项（保留默认选项）
                        departmentSelect.find('option:not(:first)').remove();
                        
                        // 添加部门选项
                        if(departments && departments.length > 0) {
                            departments.forEach(function(dept) {
                                var selected = dept.id === departmentId ? 'selected' : '';
                                departmentSelect.append(`<option value="${dept.id}" ${selected}>${dept.departmentName}</option>`);
                            });
                        }
                        
                        // 重新渲染下拉选择框
                        form.render('select');
                    },
                    error: function(xhr, status, error) {
                        console.log('获取部门数据失败:', error);
                        layer.msg('获取部门数据失败', {icon: 2});
                        // 渲染表单
                form.render('select');
                    }
                });

                form.on('submit(editUserForm)', function(data) {
                    var token = $('input[name="__RequestVerificationToken"]').val();
                    
                    var formData = {
                        Id: parseInt(data.field.Id),
                        UserName: data.field.UserName,
                        UserPhone: data.field.UserPhone,
                        UserNickName: data.field.UserNickName,
                        DepartmentId: parseInt(data.field.DepartmentId)
                    };

                    $.ajax({
                        url: '/User/UpdateUser',
                        type: 'POST',
                        data: JSON.stringify(formData),
                        contentType: 'application/json',
                        headers: {
                            'RequestVerificationToken': token
                        },
                        success: function(res) {
                            if(res === 1) {
                                layer.msg('修改成功', {
                                    icon: 1,
                                    time: 1500
                                }, function() {
                                    layer.close(index);
                                    Show();
                                });
                            } else {
                                layer.msg('修改失败', {icon: 2});
                            }
                        },
                        error: function(xhr, status, error) {
                            console.log("修改失败 - 状态:", status);
                            console.log("修改失败 - 错误:", error);
                            console.log("修改失败 - 响应:", xhr.responseText);
                            try {
                                var response = JSON.parse(xhr.responseText);
                                layer.msg('修改失败：' + (response.message || response.Message || error), {icon: 2});
                            } catch (e) {
                                layer.msg('修改失败：' + (xhr.responseText || error), {icon: 2});
                            }
                        }
                    });
                    return false;
                });
            }
        });
    }
</script>
